package codebush.service.impl;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;

import codebush.service.Get;
import codebush.service.Help;
import codebush.service.Home;

/**
 *2008-4-2
 *@author Fution Bai
 * Copyright 2007 
 */

public class HelpImpl implements Help {

	private Get get;
	private Home home;
	
	public Home getHome() {
		return home;
	}

	public void setHome(Home home) {
		this.home = home;
	}

	public Get getGet() {
		return get;
	}

	public void setGet(Get get) {
		this.get = get;
	}

	public void postRetrievedMessage(Message[] messages) {
		for (int i = 0; i < messages.length; i++) {
			try {
				String title = "no title", content = "it is empty";
				String tag = "general";
				int userId = 0;
				if (messages[i].getSubject() != null) {
					title = messages[i].getSubject();
				}
				if (messages[i].getContent() != null) {
					Part part = messages[i];
					String contentType = part.getContentType();
					if (contentType.indexOf("text/plain") > -1) {
						content = part.getContent().toString().trim();
					} else if (contentType.indexOf("multipart/alternative") > -1) {
						Multipart mp = (Multipart) part.getContent();
						for (int j = 0; j < mp.getCount(); j++) {
							BodyPart bodyPart = mp.getBodyPart(j);
							String t = bodyPart.getContentType();
							if (t.indexOf("text/plain") > -1) {
								content = bodyPart.getContent().toString().trim();
							}
						}
					}
				}
				if (messages[i].getFrom() != null) {
					String email = "";
					String from = messages[i].getFrom()[0].toString();
					int m = from.indexOf("<");
					int n = from.indexOf(">");
					if (m > -1 && n > -1) {
						email = from.substring(m + 1, n);
					} else {
						email = from;
					}
					userId = this.getGet().getUserId(email);
				}
				if (userId != 0) {
					this.getHome().postArticle(title, content, tag, userId);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}


